import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';

import '../../../../core/model/popular_series_one_model.dart';
import '../../../../core/service/request/popular_series_one_request.dart';

const gridColor = Color(0xff68739f);
const titleColor = Color(0xff8c95db);
const fashionColor = Color(0xffe15665);
const artColor = Color(0xff63e7e5);
const boxingColor = Color(0xff83dea7);
const entertainmentColor = Colors.white70;
const offRoadColor = Color(0xFFFFF59D);

class HYRadarChartSamples extends StatefulWidget {
  const HYRadarChartSamples({Key? key}) : super(key: key);

  @override
  State<HYRadarChartSamples> createState() => _HYRadarChartSamplesState();
}

class _HYRadarChartSamplesState extends State<HYRadarChartSamples> {
  int selectedDataSetIndex = -1;
  List<ListElement> _list = [];

  @override
  void initState() {
    PopularSeriesOneRequest.getPopularSeriesOneData().then((value) {
      setState(() {
        _list = value.list.sublist(0, 5);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xff231f49),
      child: ListView(
        children: [
          _list.isNotEmpty
              ? Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      GestureDetector(
                        onTap: () {
                          setState(() {
                            selectedDataSetIndex = -1;
                          });
                        },
                        child: Text(
                          "每周必看前5指标",
                          style: const TextStyle(
                            color: titleColor,
                            fontSize: 18,
                          ),
                        ),
                      ),
                      const SizedBox(height: 4),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: rawDataSets()
                            .asMap()
                            .map((index, value) {
                              final isSelected = index == selectedDataSetIndex;
                              return MapEntry(
                                index,
                                GestureDetector(
                                  onTap: () {
                                    setState(() {
                                      selectedDataSetIndex = index;
                                    });
                                  },
                                  child: AnimatedContainer(
                                    duration: const Duration(milliseconds: 300),
                                    margin:
                                        const EdgeInsets.symmetric(vertical: 2),
                                    height: 26,
                                    decoration: BoxDecoration(
                                      color: isSelected
                                          ? gridColor.withOpacity(0.5)
                                          : Colors.transparent,
                                      borderRadius: BorderRadius.circular(46),
                                    ),
                                    padding: EdgeInsets.symmetric(
                                        vertical: 4.px, horizontal: 6.px),
                                    child: Row(
                                      children: [
                                        AnimatedContainer(
                                          duration:
                                              const Duration(milliseconds: 400),
                                          curve: Curves.easeInToLinear,
                                          padding: EdgeInsets.all(
                                              isSelected ? 8 : 6),
                                          decoration: BoxDecoration(
                                            color: value.color,
                                            shape: BoxShape.circle,
                                          ),
                                        ),
                                        const SizedBox(width: 8),
                                        AnimatedDefaultTextStyle(
                                          duration:
                                              const Duration(milliseconds: 300),
                                          curve: Curves.easeInToLinear,
                                          style: TextStyle(
                                            color: isSelected
                                                ? value.color
                                                : gridColor,
                                          ),
                                          child: Expanded(
                                            child: Text(
                                              value.title,
                                              maxLines: 1,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              );
                            })
                            .values
                            .toList(),
                      ),
                      const SizedBox(height: 30),
                      AspectRatio(
                        aspectRatio: 1.3,
                        child: RadarChart(
                          RadarChartData(
                            radarTouchData: RadarTouchData(
                                touchCallback: (FlTouchEvent event, response) {
                              if (!event.isInterestedForInteractions) {
                                setState(() {
                                  selectedDataSetIndex = -1;
                                });
                                return;
                              }
                              setState(() {
                                selectedDataSetIndex = response
                                        ?.touchedSpot?.touchedDataSetIndex ??
                                    -1;
                              });
                            }),
                            dataSets: showingDataSets(),
                            radarBackgroundColor: Colors.transparent,
                            borderData: FlBorderData(show: false),
                            radarBorderData:
                                const BorderSide(color: Colors.transparent),
                            titlePositionPercentageOffset: 0.2,
                            titleTextStyle: const TextStyle(
                                color: titleColor, fontSize: 14),
                            getTitle: (index) {
                              switch (index) {
                                case 0:
                                  return '点赞';
                                case 1:
                                  return '硬币';
                                case 2:
                                  return '收藏';
                                case 3:
                                  return '分享';
                                default:
                                  return '评论';
                              }
                            },
                            tickCount: 1,
                            ticksTextStyle: const TextStyle(
                                color: Colors.transparent, fontSize: 10),
                            tickBorderData:
                                const BorderSide(color: Colors.transparent),
                            gridBorderData:
                                const BorderSide(color: gridColor, width: 2),
                          ),
                          swapAnimationDuration:
                              const Duration(milliseconds: 400),
                        ),
                      ),
                    ],
                  ),
                )
              : Container(),
        ],
      ),
    );
  }

  List<RadarDataSet> showingDataSets() {
    return rawDataSets().asMap().entries.map((entry) {
      var index = entry.key;
      var rawDataSet = entry.value;

      final isSelected = index == selectedDataSetIndex
          ? true
          : selectedDataSetIndex == -1
              ? true
              : false;

      return RadarDataSet(
        fillColor: isSelected
            ? rawDataSet.color.withOpacity(0.2)
            : rawDataSet.color.withOpacity(0.05),
        borderColor:
            isSelected ? rawDataSet.color : rawDataSet.color.withOpacity(0.25),
        entryRadius: isSelected ? 3 : 2,
        dataEntries:
            rawDataSet.values.map((e) => RadarEntry(value: e)).toList(),
        borderWidth: isSelected ? 2.3 : 2,
      );
    }).toList();
  }

  List<RawDataSet> rawDataSets() {
    int indexColor = 0;
    List<Color> colorList = [
      fashionColor,
      artColor,
      entertainmentColor,
      offRoadColor,
      boxingColor
    ];
    List<RawDataSet> rawDataSetList = [];
    for (var item in _list) {
      rawDataSetList.add(
          RawDataSet(title: item.title, color: colorList[indexColor], values: [
        item.stat["like"]!.toDouble(),
        item.stat["coin"]!.toDouble(),
        (item.stat["favorite"]! * 2).toDouble(),
        (item.stat["share"]! * 5).toDouble(),
        (item.stat["danmaku"]! * 15).toDouble(),
      ]));
      indexColor++;
    }
    return rawDataSetList;
  }
}

class RawDataSet {
  final String title;
  final Color color;
  final List<double> values;

  RawDataSet({
    required this.title,
    required this.color,
    required this.values,
  });
}

class BuildRadarChartSample01 extends StatefulWidget {
  const BuildRadarChartSample01({Key? key}) : super(key: key);

  @override
  State<BuildRadarChartSample01> createState() =>
      _BuildRadarChartSample01State();
}

class _BuildRadarChartSample01State extends State<BuildRadarChartSample01> {
  @override
  Widget build(BuildContext context) {
    return Container();
  }
}
